using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;

public class UILoader : Singleton<UILoader>
{
    [System.Serializable]
    public class UIConfig
    {
        public string uiName;          // 界面标识名称
        public bool useResourcesLoad;   // 是否使用Resources加载
        public string resourcePath;    // Resources路径
        public GameObject uiPrefab;     // 预制体直接引用
    }

    [Header("UI配置列表")]
    [SerializeField] private List<UIConfig> uiConfigs = new List<UIConfig>();

    [Header("基础配置")]
    [SerializeField] private KeyCode toggleKey = KeyCode.S; // 默认触发按键
    [SerializeField] private Canvas targetCanvas;

    private GameObject currentUIInstance;  // 当前加载的UI实例

    public void Text()
    {
        ToggleUI("FinishPanel");
    }

    /// <summary>
    /// 切换指定UI界面
    /// </summary>
    /// <param name="uiName">UI配置名称</param>
    public void ToggleUI(string uiName)
    {
        // 如果存在当前界面则关闭
        if (currentUIInstance != null)
        {
            Destroy(currentUIInstance);
            Debug.Log("已关闭当前UI界面");
            Time.timeScale = 1f;
            return;
        }

        // 查找对应的配置
        UIConfig config = uiConfigs.Find(c => c.uiName == uiName);
        if (config == null)
        {
            Debug.LogError($"未找到UI配置：{uiName}");
            return;
        }

        // 根据配置加载界面
        if (config.useResourcesLoad)
        {
            LoadFromResources(config.resourcePath);
        }
        else
        {
            LoadFromReference(config.uiPrefab);
        }

        Time.timeScale = 0f; // 暂停游戏
    }

    private void LoadFromReference(GameObject prefab)
    {
        if (prefab == null)
        {
            Debug.LogError("预制体引用为空");
            return;
        }

        EnsureCanvasExists();
        currentUIInstance = Instantiate(prefab, targetCanvas.transform);
        InitializeUI(currentUIInstance);
    }

    private void LoadFromResources(string path)
    {
        GameObject prefab = Resources.Load<GameObject>(path);
        if (prefab == null)
        {
            Debug.LogError($"资源加载失败：{path}");
            return;
        }

        EnsureCanvasExists();
        currentUIInstance = Instantiate(prefab, targetCanvas.transform);
        InitializeUI(currentUIInstance);
    }

    private void EnsureCanvasExists()
    {
        if (targetCanvas == null)
        {
            targetCanvas = FindObjectOfType<Canvas>();
            if (targetCanvas == null) CreateNewCanvas();
        }
    }

    private void CreateNewCanvas()
    {
        GameObject canvasGO = new GameObject("DynamicCanvas");
        targetCanvas = canvasGO.AddComponent<Canvas>();
        canvasGO.AddComponent<CanvasScaler>();
        canvasGO.AddComponent<GraphicRaycaster>();
        Debug.Log("已自动创建新Canvas");
    }

    private void InitializeUI(GameObject uiInstance)
    {
        // 设置全屏显示
        RectTransform rt = uiInstance.GetComponent<RectTransform>();
        if (rt != null)
        {
            rt.anchoredPosition = Vector2.zero;
            rt.localScale = Vector3.one;
            rt.sizeDelta = Vector2.zero;
        }

        // 通用初始化接口
        IInitializableUI initializable = uiInstance.GetComponent<IInitializableUI>();
        if (initializable != null)
        {
            initializable.InitializePanel();
        }
        else
        {
            Debug.LogWarning("该UI未实现初始化接口");
        }

        Debug.Log($"{uiInstance.name} 初始化完成");
    }
}

// UI初始化接口
public interface IInitializableUI
{
    void InitializePanel();
}